package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {
        //设置属性
        video.setCreated(System.currentTimeMillis());
        video.setVid(idWorker.getNextId("video"));
        video.setText("我是帅哥");
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    //根据vid查询数据列表
    @Override
    public List<Video> findVideosByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return videos;
    }
    //分页查询视频列表
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return videos;
    }

    //根据ID查询个人视频列表
    @Override
    public PageResult findVideosByVid(Integer page, Integer pagesize, Long uid) {
        Criteria criteria = Criteria.where("userId").is(uid);
        Query query = Query.query(criteria);
        //查询总数量
        long count = mongoTemplate.count(query, Video.class);
        //分页查询
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize, Math.toIntExact(count),videos);
    }
}
